import threading

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QMainWindow

from AccelGLWidget import AccelGLWidget, AccelPlotGLWidget
from adx357 import Ui_MainWindow
from serial_process import DataLogger


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.opengl_widget = AccelPlotGLWidget(self)
        self.opengl_widget1 = AccelPlotGLWidget(self)
        self.opengl_widget2 = AccelPlotGLWidget(self)
        self.opengl_widget.setcolor("x")
        self.opengl_widget1.setcolor("y")
        self.opengl_widget2.setcolor("z")

        layout = self.gridLayout_3
        layout.addWidget(self.opengl_widget)
        layout.addWidget(self.opengl_widget1)
        layout.addWidget(self.opengl_widget2)


        self.logger = DataLogger(port='COM4', baudrate=921600)
        threading.Thread(target=self.logger.start_streaming, daemon=True).start()

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_value_display)
        self.timer.start(50)

    def update_accel_display(self):
        with self.logger.buffer_lock:
            if self.logger.buffer['X'] and self.logger.buffer['Y'] and self.logger.buffer['Z']:
                x = self.logger.buffer['X'][-1]
                y = self.logger.buffer['Y'][-1]
                z = self.logger.buffer['Z'][-1]
                self.opengl_widget.set_accel(x, y, z)

    def update_value_display(self):
        with self.logger.buffer_lock:
            if self.logger.buffer['X'] and self.logger.buffer['Y'] and self.logger.buffer['Z']:
                x = self.logger.buffer['X'][-1]
                y = self.logger.buffer['Y'][-1]
                z = self.logger.buffer['Z'][-1]
                self.opengl_widget.add_point(x)
                self.opengl_widget1.add_point(y)
                self.opengl_widget2.add_point(z)




